package com.xframe.common.core.aop;



import com.xframe.xdal.core.annotation.XExecTime;
import com.xframe.xdal.core.util.XReflect;
import lombok.extern.log4j.Log4j2;

@Log4j2
public class ExecTimeDecoration extends BaseDecoration{

    private XExecTime execTime = null;
    private Class<?> typeName = null;
    private Long startTime = 0L;
    private Long endTime = 0L;

    public ExecTimeDecoration(){
        setExecOrder(900);
    }

    @Override
    public boolean testMethod(XAOPContext context) {
        execTime = XReflect.getMethodAnnotation(context.getMethod(),XExecTime.class);
        typeName = context.getMethod().getDeclaringClass();
        if(execTime == null) {
            execTime = typeName.getAnnotation(XExecTime.class);
        }
        return execTime != null;
    }

    @Override
    public void init(XAOPContext context) {

        super.init(context);
    }


    @Override
    public void beforeExecution(XAOPContext context) {
        startTime = System.currentTimeMillis();
        super.beforeExecution(context);
    }

    @Override
    public void afterExecution(XAOPContext context) {
        super.afterExecution(context);
    }

    @Override
    public void finallyComplete(XAOPContext context) {
        endTime = System.currentTimeMillis();
        log.info(String.format("方法 %s.%s 执行成功,耗时 %d 毫秒.",typeName.getSimpleName(),context.getMethod().getName(),endTime - startTime));
        super.finallyComplete(context);
    }

    @Override
    public void exceptionHandler(XAOPContext context){
        endTime = System.currentTimeMillis();
        log.info(String.format("方法 %s.%s 执行失败,耗时 %d 毫秒.",typeName.getSimpleName(),context.getMethod().getName(),endTime - startTime));
        super.exceptionHandler(context);
    }

    @Override
    public BaseDecoration buildeNew() {
        return new ExecTimeDecoration();
    }

}
